using System;
using UnityEngine;
using UnityEngine.UIElements;
using Void = Utility.GameEvents.Scriptable.Integrated.Void;

public class GameManager : MonoBehaviour {
    private TurnManager m_turnManager;
    private int m_FoodAmount = 100;
    
    [Utility.Attributes.NotNull] public BoardManager m_boardManager;
    [Utility.Attributes.NotNull] public PlayerController m_playerController;
    
    private UIDocument m_gameUiDoc;
    
    [Header("Food event")]
    [SerializeField] private Utility.GameEvents.Scriptable.Integrated.IntGameEvent m_onTakeFood;

    private Label m_FoodLabel;

    private void OnEnable() {
        m_onTakeFood.Register(onTakeFood_Handler);
    }

    private void onTakeFood_Handler(int foodAmount) {
        m_FoodAmount += foodAmount;
        m_FoodLabel.text = "Food : " + m_FoodAmount;
    }

    private void OnDisable() {
        m_onTakeFood.Unregister(onTakeFood_Handler);
    }



    void Start() {
        if (!m_boardManager) return;
        if (!m_playerController) return;
        
        m_FoodAmount = GameSettings.Instance.DefaultFood;
        
        //UI
        m_gameUiDoc = GameObject.FindFirstObjectByType<UIDocument>();
        m_FoodLabel = m_gameUiDoc.rootVisualElement.Q<Label>("FoodLabel");
        m_FoodLabel.text = "Food : " + m_FoodAmount;
        
        m_turnManager = new TurnManager();
        
        m_boardManager.Init();
        m_playerController.Init(m_boardManager, new Vector2Int(1, 1));
        
        m_playerController.PlayerTurnDoneEvent.Register(PlayerTurnDoneEvent_Handler);
        m_turnManager.onTick += onTurnHappen;
    }

    private void OnDestroy() {
        m_playerController.PlayerTurnDoneEvent.Unregister(PlayerTurnDoneEvent_Handler);
        m_turnManager.onTick -= onTurnHappen;
    }

    private void onTurnHappen() {
        m_FoodAmount -= 1;
        m_FoodLabel.text = "Food : " + m_FoodAmount;
    }
    
    private void PlayerTurnDoneEvent_Handler(Void _) {
        if (m_boardManager.TryGetCellData(m_playerController.CurrentCellPosition, out var cellData)) {
            cellData.ContainedObject?.PlayerEntered();
        }
        m_turnManager.Tick();
    }
}
